# -*- coding:utf-8 -*-
import struct,Pluto,fnmatch,os,codecs

fl=Pluto.walk('Text')
for fn in fl:
    if not fnmatch.fnmatch(fn,'*.lz77Ex'):
        continue
    print fn
    fp=open(fn,'rb')
    fp.seek(8)
    size=struct.unpack('i',fp.read(4))[0]
    end=struct.unpack('i',fp.read(4))[0]+0xc
    tar=codecs.open(fn+'.txt','wb','utf_16')
    for i in xrange(0xc,end,4):
        tar.write('No.%d\r\n'%((i-0xc)/4)+u'－'*18+'\r\n')
        fp.seek(i)
        offset=struct.unpack('i',fp.read(4))[0]+0xc
        nextoffset=struct.unpack('i',fp.read(4))[0]+0xc
        if i==end-4:
            nextoffset=size
        fp.seek(offset)
        string=[]
        while True:
            newoffset=fp.tell()
            if newoffset>=nextoffset:
                break
            char=struct.unpack('H',fp.read(2))[0]
            if char==10:
                string.append('\r\n')
            elif char==1:
                fp.seek(newoffset)
                for j in xrange(0,0xc,2):
                    string.append(u'{%04x}'%(struct.unpack('H',fp.read(2))[0]))
                string.append('\r\n')
            elif char<0x20:
                string.append(u'{%04x}'%char)
            elif char==0xffff:
                string.append(u'{FFFF}')
            else:
                string.append(unichr(char))
        tar.write(''.join(string)+'\r\n'+u'－'*18+'\r\n'*2)
    fp.close()
    tar.close()